package cn.ztydata.teachingsystem.heaven.dao.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 问题回答量和浏览量
 *
 * @author lyj
 * @since 2015-3-27
 */
@Repository
public class QuestionPvAnCountDao {

    @Resource(name = "stringRedisTemplate")
    protected RedisTemplate redisTemplate; //sdr-Redis模版

    protected static Logger logger = LoggerFactory.getLogger(ExerciseCountDao.class); //日志记录器

    private static final String QUESTION_COUNT = "question:total";

    public static final String VIEWS = "pv"; //浏览量
    public static final String ANSWER_COUNT = "answerCount"; //回答量


    /**
     * 递增问题的浏览量或回答量
     *
     * @param questionId 习题ID
     * @param filed 字段名称
     * @return Long
     * @author lyj
     * @since 2015-3-27
     */
    public Long increment(final long questionId, final String filed, final int addOrSub) {
        //获取hash操作
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();

        logger.debug("递增问题的浏览量或回答量");
        return hashOperations.increment(KeyUtils.generateKey(QUESTION_COUNT, questionId), filed, addOrSub);
    }


    /**
     * 读取浏览量、回答量
     *
     * @param questionId 问题ID
     * @param filed 字段名称
     * @return Long
     * @author lyj
     * @since 2015-3-27
     */
    public List<Long> getCount(final long questionId, final String... filed){
        //获取hash操作
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();

        //注意读取的数据顺序是和传进来的字段顺序相对应的。
        List<String> counts = hashOperations.multiGet(KeyUtils.generateKey(QUESTION_COUNT, questionId), Arrays.asList(filed));

        //转换数据格式
        List<Long> reCount = new ArrayList<>();
        logger.debug("绑定浏览量、回答量");
        for (String count : counts){
            reCount.add(count == null ? 0 : Long.valueOf(count));
        }

        logger.debug("读取浏览量、回答量");
        return reCount;
    }

}
